/*-
 * Phonebook.java
 *
 * $LastChangedBy:  $
 * $LastChangedRevision:  $
 * $LastChangedDate:  $
 * $HeadURL: $
 *
 * Copyright (c) 2008, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.intention.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.attention.PhonebookEntry;
import com.googlecode.attention.PhonebookEntryImpl;
import com.googlecode.attention.sms.pdu.Address;
import com.googlecode.attention.util.SMSCharacterSet;
import com.googlecode.attention.util.Settings;

import static com.googlecode.attention.intention.IntentionLogStatements.*;


public class Phonebook {

  private final Settings settings;
  private final ArrayList<PhonebookEntry> entries;
  
  public Phonebook(final Settings settings) {
    this.settings = settings;
    entries = new ArrayList<PhonebookEntry>();
  }
  
  public void addEntries(final PhonebookEntry[] entries) {
    for (PhonebookEntry entry : entries) {
      this.entries.add(entry);
    }
  }
  
  public String findName(final Address address) {
    if (address == null) {
      return null;
    }
    final String number = address.getNumber();
    String output = null;
    int matchTolerance = settings.getInteger("phonebook_match_tolerance");
    char[] input = number.toCharArray();
    
    ENTRIES: for (PhonebookEntry phonebookEntry : entries) {
      char[] entry = phonebookEntry.getNumber().toCharArray();
      // we could compare the TOA here if necessary
      // TODO could make the search faster
      int iLength = input.length;
      int eLength = entry.length;
      int matchCount = 0;
      int matchMax = iLength;
      while (iLength > 0 && eLength > 0) {
        if (input[--iLength] == entry[--eLength]) {
          matchCount++;
        } else {
          break;
        }
      }
      if (matchMax > 0) {
        double match = matchCount * 100 / matchMax;
        if (match >= matchTolerance) {
          output = phonebookEntry.getName();
          break ENTRIES;
        }
      }
    }
    
    return (output == null ? number : SMSCharacterSet.gsmToUnicode(output));
  }
  
  
  
  public void readEntriesFromFile() {
    final File file = new File(settings.getString("numbers_file"));
    if (!file.exists()) {
      INTENTION_004.log(file.getPath());
    } else if (!file.isFile()) {
      INTENTION_002.log(file.getPath());
    } else if (!file.canRead()) {
      String userName = "";
      try {
        userName = " " + System.getProperty("user.name");
      } catch (SecurityException ignored) {}
      INTENTION_003.log(userName, file.getPath());
    } else {
      try {
        final BufferedReader reader = new BufferedReader(new FileReader(file));
        
        try {
          String line;
          while ((line = reader.readLine()) != null) {
            parseText(line);
          }
        } catch (IOException e) {
          INTENTION_005.log(e);
        }
      } catch (FileNotFoundException e) {
        /* Should never happen with the checks above */
        INTENTION_001.log(file.getPath(), e.getMessage());
      }
    }
  }
  
  private void parseText(final String text) {
    final Pattern pattern = Pattern.compile(
        "\\+CPBR: ([0-9]+),\"([+0-9A-Za-z]+)\",([0-9]+),\"([^\"]+)\"");
    final Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
      final int memoryIndex = Integer.parseInt(matcher.group(1));
      final String number = matcher.group(2);
      final int toa = Integer.parseInt(matcher.group(3));
      final String name = matcher.group(4);
      entries.add(new PhonebookEntryImpl(memoryIndex, number, toa, name));
    }
  }
  
  public void dumpTo(final PrintStream out) {
    for (PhonebookEntry entry : entries) {
      out.println("+CPBR: " + entry.getMemoryIndex()
          + ",\"" + entry.getNumber()
          + "\"," + entry.getTypeOfAddress()
          + ",\"" + entry.getName() + "\"");
    }
  }
}
